# -*- coding: utf-8 -*-
"""
A class to interface with the fortran utilities.
"""
import __hs1
from numpy import zeros,array
from math import sqrt,pi

Inf = 99999999
a = array
class FortranInterface(object):
    def __init__(self,module,n,me=0,mi=0,xu=None,xl=None,x0=None,fb=None,descr='',f0=None):
        self.module = module
        self.n  = n
        self.mi = mi
        self.me = me
        self.xu = xu
        self.xl = xl
        self.x0 = x0
        self.fb = fb
        self.descr = descr
        self.f0 = f0
        
    def test(self):
        fe = self.__call__(self.x0)
        print self.descr,'  ',self.f0,' == ',fe,
        if abs(self.f0 - fe) < 1e-6:
            print "True"
        else:
            print "False"
        
    def x2fx(self,x):
        fortranx = zeros(301)
        fortranx[:self.n] = x
        return fortranx
        
    def __call__(self,x):
        fx = self.module.ef(self.x2fx(x))
        return fx
        
    def g(self,x):
        return self.module.egradf(self.x2fx(x))[:self.n]
        
    def cin(self,x):
        """
        Calculates the inequality constraints and returns them
        """
        cin = zeros(self.mi)
        for i in range(self.mi):
            cin[i] = self.module.eg(i+1,self.x2fx(x))
        return cin
        
    def ceq(self,x):
        ceq = zeros(self.me)
        for i in range(self.me):
            ceq[i] = self.module.eh(i+1,self.x2fx(x))
        return ceq
    

        
p1 = FortranInterface(__hs1,2,mi=1,descr='PBR-T1-1',
                    xl=a([-Inf,-1.5]),
                    xu=a([Inf,Inf]),
                    x0=a([-2.,1.]),
                    f0=909.0)
                    
import __hs5                    
p5 = FortranInterface(__hs5,2,mi=4,descr='GBR-T1-1',
                      xl=a([-1.5,-3.]),
                      xu = a([4.,3.]),
                      x0 = a([0.,0.]),
                      f0 = 1.,
                      fb = -0.5 * sqrt(3) - pi/3)